package cn.sanshuilin.kst.system.provider.serviceimpl;


import cn.sanshuilin.kst.common.utils.LogPrinter;
import cn.sanshuilin.kst.common.utils.ResourceHelper;
import cn.sanshuilin.kst.common.utils.Utility;
import cn.sanshuilin.kst.system.provider.bean.Dict;
import cn.sanshuilin.kst.system.provider.core.CLang;
import cn.sanshuilin.kst.system.provider.write.dao.DictDao;
import cn.sanshuilin.kst.system.provider.write.dao.DictReq;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @author greenlee
 * @version v1.0
 * @create 创建时间: 2017-11-27 19:48
 * Copyright 2017  by 三水林科技有限公司
 **/
@Service
public class DictService {

    @Autowired
    private DictDao dao;

    @Autowired
    private DictReq req;

    @Autowired
    private CLangService cLangService;


    private static List<Dict> allDicts = null;
    private static List<Dict> allDictsSortByID = null;
    private static ArrayList allDictIDs = null;
    private static String LangCodeSequenceNo = "";
    private static String LangCodeSequenceID = "";


    public Dict getNewDict() {

        Object strMaxID = req.getNewDict();
        int nID = Utility.toSafeInt(strMaxID, -1);

        return getDictFromDB(nID);

    }

    // / <summary>
    // / 保存一个字典当
    // / </summary>
    // / <param name="dict"></param>
    public void saveDict(Dict dict) {
        Session session = null;

//            if (dict.getId() == null || dict.getId() == 0) {
            if ( dict.getId() == 0) {
                // 设置编码,只是新增时需要设置
                setCode(dict, session);
                if(dict.getStatusId() == null ){
                    dict.setStatusId(0);
                }
                if(dict.getSequenceNo() == null){
                    dict.setSequenceNo(1);
                }
                if(dict.getIsReadonly() == null){
                    dict.setIsReadonly(0);
                }
                dao.saveAndFlush( dict);
            } else {
                dao.update(dict.getId(),dict.getCode());
            }

    }

    // 设置编码
    private Dict setCode(Dict dict, Session session) {
        //

        String strCode = (String) req.setCode(dict);

        // 如果当前级别最大编码不存在,则设置为ParentCode + 0001
        if (StringUtils.isEmpty(strCode) || strCode.length() < 4) {
            Dict parentDict = (Dict) session.get(Dict.class, (Serializable) dict.getParentId());
            if (parentDict != null) {
                strCode = parentDict.getCode();
            } else {
                strCode = "";
            }

            strCode += "0001";
        } else {
            String strEndCode = strCode.substring(strCode.length() - 4, strCode.length());
            String strNextCode = StringUtils.leftPad( Utility.toSafeString(Utility.toSafeInt(strEndCode) + 1), 4, '0');

            strCode = strCode.substring(0,strCode.length() -4) + strNextCode;
        }
        dict.setCode(strCode);

        return dict;
    }

    // / <summary>
    // / 根据ID删除一个字典档
    // / </summary>
    // / <param name="nDictID"></param>
    public void deleteDictFromDB(int nDictID) {
        dao.removeById( nDictID + "");
    }
    // / <summary>
    // / 根据分类取得字典列表
    // / </summary>
    // / <param name="dictCategory"></param>
    // / <returns></returns>
    public  List<Dict> getNextDicts(Integer nParentID) {
        List<Dict> dicts = new ArrayList<Dict>();
        for (Dict dict : getAllDicts()) {
            if (dict.getParentId().equals(nParentID)) {
                dicts.add((Dict)dict.clone());
            }
        }
        return dicts;
    }

    // / <summary>
    // / 清除内存中的字典档
    // / </summary>
    public static void clear() {
        allDicts = null;
        allDictIDs = null;
        allDictsSortByID = null;
    }


    public int getMaxSequence(int nParentID) {

        Object strMaxID = req.getMaxSequence(nParentID);
        int nMaxID = Utility.toSafeInt(strMaxID, 1) + 2;

        return nMaxID;

    }


    public String getDictNamesByIDs(String strDictIDs) {
        String strNames = "";
        if (strDictIDs != null && !"".equals(strDictIDs)) {
            String[] strIDs = Utility.getStrArray(strDictIDs);
            for (String strID : strIDs) {
                if (!"".equals(strNames)) {
                    strNames += ",";
                }
                strNames += getDictNameByID(new Integer(Utility.toSafeInt(strID)));
            }
        }
        return strNames;
    }


    public Dict getDictByID(Integer nDictID) {

        Dict dict = null;
        if (nDictID == null || nDictID <= 0) {
            return null;
        }

        try {
            int nIndex = Collections.binarySearch(getAllDictIDs(), nDictID);
            dict = getAllDictsSortByID().get(nIndex);
            dict.setParentName(getDictNameByID(dict.getParentId()));
        } catch (Exception e) {
            //LogPrinter.info("getdictbyid:"+  e.getMessage());
        }
        if (dict != null) {
            return dict;
        } else {
            return null;
        }
    }


    public String getDictNameByID(Integer nDictID) {
        try {
            if (nDictID != null && nDictID > 0) {
                String name = ResourceHelper.getValue("Dict_" + nDictID);
                if (StringUtils.isEmpty(name)) {
                    Dict d = getDictFromDB(nDictID);
                    LogPrinter.info("miss:" + d.getId());
                    if (d != null) {
                        name = d.getName();
                    }
                }
                return name;
            }
            return "";
        } catch (Exception err) {
            return "";
        }
    }

    public Dict getDictFromDB(int nDictID) {
        return dao.findById(nDictID);
    }

    private List<Dict> getAllDictsSortByID() {
        if (allDictsSortByID == null) {
            allDictsSortByID = dao.findAll();
        }
        try {
            String v = cLangService.getCurrentLangID();
            if (!LangCodeSequenceID.equals(v)) {
                for (Dict dict : allDictsSortByID) {
                    String strName = getDictNameByID(dict.getId());
                    if (StringUtils.isNotEmpty(strName)) {
                        dict.setName(strName);
                    }
                }
                LangCodeSequenceID = v;
            }
        } catch (Exception err) {
            //LogPrinter.info("lang exception");
        }

        return allDictsSortByID;
    }

    public List<Dict> getAllDicts(int nParentID) {
        List<Dict> dicts = new ArrayList<Dict>();
        List<Dict> all = getAllDicts();
        if (nParentID == 0) {
            for (Dict dict : all) {
                dicts.add((Dict) dict.clone());
            }
        } else {
            Dict parent = getDictByID(new Integer(nParentID));
            if (parent != null) {
                for (Dict dict : all) {
                    if (dict.getCode().startsWith(parent.getCode()) && !dict.getCode().equals(parent.getCode())) {
                        dicts.add((Dict) dict.clone());
                    }
                }
            }
        }
        return dicts;
    }

    // / <summary>
    // / 取得所有字典对象
    // / </summary>
    // / <returns></returns>
    private List<Dict> getAllDicts() {
        if (allDicts == null) {
//            allDicts = (List<Dict>) dao.getAll(Dict.class, "SequenceNo");
            allDicts = (List<Dict>) dao.findAll();
        }

        String v = Utility.toSafeString(CLang.getCurrentLangID());
        if (!LangCodeSequenceNo.equals(v)) {
            for (Dict dict : allDicts) {
                String strName = getDictNameByID(new Integer(dict.getId()));
                if (StringUtils.isNotEmpty(strName)) {
                    dict.setName(strName);
                }
            }
            LangCodeSequenceNo = v;
        }
        return allDicts;
    }

    private ArrayList getAllDictIDs() {
        if (allDictIDs == null) {
            allDictIDs = new ArrayList();
            List<Dict> allDictsSortByIDs = getAllDictsSortByID();
            for (Dict dict : allDictsSortByIDs) {
                DictService.allDictIDs.add(dict.getId());
            }
            //Collections.sort(DictManager.allDictIDs);
        }
        return allDictIDs;
    }


}
